<template>
  <div>
    <div class="login-container">
      <div class="left-bg"></div>
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
        <div class="title-container">
          <div class="sys-title">CRM</div>
          <div class="sub-title" v-if="isScancode">扫码下载APP</div>
          <div class="main-title" v-else>账号密码登录</div>
        </div>
        <div class="scancode-container" v-if="isScancode">
          <div class="content">
            <div>
              <img :src="ios" style="text-align: center" />
              <div style="margin-top: 10px">苹果下载二维码</div>
            </div>
            <div v-if="isAndirod">
              <img :src="andirod" style="text-align: center" />
              <div style="margin-top: 10px">安卓下载二维码</div>
            </div>
          </div>
          <el-button class="close-btn" @click="isScancode = false">关闭</el-button>
        </div>
        <div v-else class="form-container">
          <el-form-item prop="username">
            <span class="svg-container">
              <img src="@/assets/images/account.png" class="account" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <span class="svg-container">
                <img src="@/assets/images/key.png" class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>
          <div class="loginSet">
            <el-checkbox v-model="isAutoLogin">自动登录</el-checkbox>
            <span class="forget" @click="ForgetPassword()">忘记密码？</span>
          </div>
          <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin" class="loginBtn">登录</el-button>
          <div class="mobile">
            <div class="mobile-item" @click="isScancode = true">
              <img src="~@/assets/images/ios.png" />
              <span>ios版</span>
            </div>
            <div class="mobile-item" @click="isScancode = true">
              <img src="~@/assets/images/andriod.png" />
              <span>Android版</span>
            </div>
          </div>
        </div>
      </el-form>
      <div class="footer">福建桔子信息科技有限公司提供技术服务支持</div>
    </div>
    <reset-pwd-dialog
      v-if="passwordVisible_if"
      :dialogVisible="passwordVisible_if"
      @handleDialogSubmit="handlePasswordDialogSubmit"
      @handleDialogCancle="handlePasswordDialogCancle"
    ></reset-pwd-dialog>
     <!-- 修改密码 -->
     <UpdatePwdDialog
      v-if="updatePasswordVisible_if"
      :dialogVisible="updatePasswordVisible_if"
      :name="loginForm.username"
      @handleDialogSubmit="handleUpdatePasswordDialogSubmit"
      @handleDialogCancle="handleUpdatePasswordDialogCancle"
    ></UpdatePwdDialog>
  </div>
</template>

<script>
// import SocialSign from './components/SocialSignin'
import resetPwdDialog from './components/resetPwdDialog.vue'
//import ResetPassword from '../components/ResetPassword'
import UpdatePwdDialog from './components/updatePwdDialog'
import QRCode from 'qrcode'
import { getAppVersions } from '@/api/appVersion'
import {isLoginBefore} from '@/api/user'
export default {
  name: 'Login',
  components: { resetPwdDialog,UpdatePwdDialog },
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   if (!validUsername(value)) {
    //     callback(new Error('Please enter the correct user name'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validatePassword = (rule, value, callback) => {
    //   if (value.length < 6) {
    //     callback(new Error('The password can not be less than 6 digits'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      andirod: '',
      ios: '',
      isAndirod: false,
      isScancode: false,
      loginForm: {
        // username: 'cys1_liuhao',
        // username: 'admin',
        // password: '1q2w3E*'
        username: '',
        password: '',
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      passwordVisible_if: false,
      isAutoLogin: false,
      updatePasswordVisible_if:false,
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true,
    },
  },
  created() {
    this.init()
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    async init() {
      return getAppVersions().then(res => {
        const data = res && res.items
        this.$nextTick(() => {
          this.isAndirod = data[0].fullPackageUpdate
          QRCode.toDataURL(data[0].packageAddress, { width: 150, margin: 1 }).then(res => {
            this.andirod = res
          })
          QRCode.toDataURL('https://apps.apple.com/cn/app/%E9%95%94%E9%91%AB%20Link/id6503027870', { width: 150, margin: 1 }).then(res => {
            this.ios = res
          })
        })
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(
              res => {
                // console.log(res)
                // this.$router.push({
                //   // path: this.redirect || '/',
                //   // query: this.otherQuery
                //   path: '/',
                // })
                this.loading = false
                 //初始密码，强制修改
                 isLoginBefore().then(res => {
                  if(!res) {
                    this.updatePasswordVisible_if = true;
                  } else {
                    this.$router.push({
                      path: '/',
                  });
                  }
                })
              },
              err => {
                this.$message({
                  message: err.response.data.error_description,
                  type: 'error',
                })
                this.loading = false
              }
            )
            .catch(() => {
              this.loading = false
            })
          // this.$store.dispatch("user/login",this.loginForm).then(res => {
          //   if(!res.error){
          //       this.$router.push({ path: this.redirect || '/' })
          //       this.loading = false
          //     }
          //   },err =>{
          //     this.$message({
          //       message:err.response.data.error_description,
          //       type:'error'
          //     })
          //     this.loading = false
          //   }).catch(() => {
          //     this.loading = false
          // })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    ForgetPassword() {
      this.passwordVisible_if = true
    },
    handlePasswordDialogSubmit() {
      this.passwordVisible_if = false
    },
    handlePasswordDialogCancle() {
      this.passwordVisible_if = false
    },
    handleUpdatePasswordDialogSubmit() {
      console.log(123);
      this.$router.push({
        path: this.redirect || "/",
        query: this.otherQuery,
      });
      this.updatePasswordVisible_if = false;
    },
    handleUpdatePasswordDialogCancle() {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
      this.updatePasswordVisible_if = false;
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #fff;
$light_gray: #666;
$cursor: #666;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background-image: url('~@/assets/images/bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border-radius: 6px;
    border: 2px solid #e8e9ef;
    margin-bottom: 0.32rem;
    // width: 3.58rem;
  }
  .el-form-item__error {
    padding-top: 0.1rem;
  }
  .footer {
    position: fixed;
    bottom: 5px;
    width: 100%;
    text-align: center;
    color: #999999;
    font-size: 14px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.left-bg {
  width: 12rem;
  height: 100vh;
}

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: #fff;
  overflow: hidden;
  display: flex;

  .login-form {
    background-image: url('~@/assets/images/kuang.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    margin-top: 2rem;
    padding: 0.4rem 0.2rem;
    height: 5.8rem;
    width: 4rem;
    .company {
      width: 1.54rem;
      height: 0.42rem;
      background-image: url('~@/assets/images/bingang.png');
      background-size: contain;
      background-repeat: no-repeat;
      margin-bottom: 0.32rem;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    .account {
      height: 13.6px;
      height: 13.6px;
    }
    .password {
      height: 13.6px;
      height: 13.6px;
    }
  }

  .title-container {
    position: relative;
    font-family: Microsoft YaHei;
    // width: 3.58rem;
    .sys-title {
      font-size: 0.18rem;
      color: #0076ff;
      transform: rotate(45deg);
      width: 0.25rem;
      position: absolute;
      top: -0.15rem;
      right: 0rem;
    }
    .title {
      font-size: 50px;
      color: #333;
      margin: 0;
      padding-bottom: 0.8rem;
      text-align: left;
      font-weight: bold;
    }
    .sub-title {
      text-align: center;
      padding: 0.2rem 0 0 0;
      color: #121218;
      font-size: 22px;
    }
    .main-title {
      text-align: center;
      padding: 0.15rem 0 0.2rem 0;
      color: #121218;
      font-size: 22px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .loginBtn {
    margin-top: 0.24rem;
    width: 100%;
    height: 0.5rem;
    // padding: 17px 20px;
  }
  .loginSet {
    // width: 3.58rem;
    vertical-align: middle;
    display: flex;
    justify-content: space-between;
    .forget {
      cursor: pointer;
      color: #0076ff;
      font-size: 14px;
    }
  }
  .mobile {
    // width: 3.58rem;
    vertical-align: middle;
    display: flex;
    justify-content: space-between;
    padding: 0.3rem 0.4rem;
    .mobile-item {
      width: 1rem;
      text-align: center;
      span {
        display: block;
        padding: 0.1rem 0;
      }
    }
    img {
      width: 0.6rem;
    }
  }
}
.scancode-container {
  text-align: center;
  padding: 0 0.2rem;
  box-sizing: border-box;
  .content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    padding: 0.8rem 0;
    img {
      width: 1.5rem;
    }
  }
  .close-btn {
    width: 100%;
    height: 0.5rem;
    margin: 0.24rem auto;
    border-radius: 0;
    border: 1.5px solid #b6b6b6;
    font-size: 0.16rem;
    // padding: 17px 20px;
  }
}
</style>
